//
//  UpIDCodeController.m
//  NtoccDriverNew
//
//  Created by 张天兴 on 2025/7/4.
//  Copyright © 2025 GCY. All rights reserved.
//

#import "UpIDCodeController.h"
#import "TZImagePickerController.h"
#import "IDentityCodeController.h"
@interface UpIDCodeController ()<TZImagePickerControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic, strong) UIImagePickerController *imagePickerController;
@property (nonatomic, strong) NSString *indexStr;
@property (nonatomic, strong) NSString *fistImag;
@property (nonatomic, strong) NSString *twoImag;
@property (nonatomic, strong) NSString *sfName;
@property (nonatomic, strong) NSString *sfNumber;
@end

@implementation UpIDCodeController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setTitle:@"身份信息"];
    self.topNHeight.constant = 15;
    self.comittButton.layer.masksToBounds = YES;
    self.comittButton.layer.cornerRadius = 10;
    [self.sfzZButton addTarget:self action:@selector(sfzZButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.sfzFButton addTarget:self action:@selector(sfzZButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    self.sfzZButton.tag = 101;
    self.sfzFButton.tag = 102;
    self.view.backgroundColor = BackgroundColor;
}


- (void)sfzZButtonAction:(UIButton *)btn{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    if (btn.tag == 101) {
        self.indexStr = @"1";
    }else{
        self.indexStr = @"2";
    }
    //取消
    UIAlertAction *changeAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
        if (btn.tag == 101) {
            [self pushPhotoViewEvent:@"1"];
        }else{
            [self pushPhotoViewEvent:@"2"];
        }
       
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action){
        if (btn.tag == 101) {
            [self checkCameraPermission];
        }else{
            [self checkCameraPermission];
        }
       
    }];
    
    [alertController addAction:changeAction];
    [alertController addAction:cancelAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
}
- (IBAction)comittButton:(UIButton *)sender {
    if(self.fistImag != nil && self.twoImag != nil){
        IDentityCodeController *vc = [[IDentityCodeController alloc] init];
        vc.name = self.sfName;
        vc.IDCod = self.sfNumber;
        vc.idnoFrontImg = self.fistImag;
        vc.idnoBackImg = self.twoImag;
        vc.isOldType = self.isOldType;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)pushPhotoViewEvent:(NSString *)str {
    
    [SystemPermissionsToolObject determineLatestPermissionsOfTheLocalAlbum];
    
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 columnNumber:4 delegate:self pushPhotoPickerVc:YES];
    imagePickerVc.allowPickingVideo = NO;
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        
        NSArray *imgArr = [NSArray array];
        
        ///是否加入水印（暂时废弃）
        if (_isAddWatermark) {
            //            UIImage *watermarkImage = [DCSpeedy addWatermarkToPicture:[photos firstObject] :@"" :CJStringWithFormat(@"经纬度：%@", _latitudeLongitudeString)];
            //            imgArr = @[watermarkImage];
            imgArr = photos;
        } else {
            imgArr = photos;
        }
        
        NSString *uploadUrl = CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-tps-api",[ReAddressDynamic shared].baseUrl], FILE_UPLOAD);

        
        [HTTPManager postUploadFiles:uploadUrl file:imgArr fileName:@"file" withVC:self netName:@"文件上传" success:^(id response, NSString *msg) {
            if ([str isEqualToString:@"1"]) {
                [self.sfzZButton sd_setBackgroundImageWithURL:response[@"data"] forState:(UIControlStateNormal)];
                self.fistImag = response[@"data"];
                [self OCRNetworking:response[@"data"]];
            }else{
                [self.sfzFButton sd_setBackgroundImageWithURL:response[@"data"] forState:(UIControlStateNormal)];
                self.twoImag = response[@"data"];
                [self OCRNetworking:response[@"data"]];
            }
            
            
        } failure:^(NSInteger code, NSString *msg) {
            
        }];
        
    }];
    imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

#pragma mark - Camera(检查相机权限方法)
- (void)checkCameraPermission {
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (status == AVAuthorizationStatusNotDetermined) {
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if (granted) {
                [self takePhoto];
            }
        }];
    } else if (status == AVAuthorizationStatusDenied || status == AVAuthorizationStatusRestricted) {
        
        [self alertAlbum];//如果没有权限给出提示
    } else {
        [self takePhoto];//有权限进入调起相机方法
    }
}
- (void)takePhoto {
#pragma mark - 07.判断相机是否可用，如果可用调起
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        self.imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        dispatch_async(dispatch_get_main_queue(), ^{
            [self presentViewController:self.imagePickerController animated:YES completion:^{
                
            }];
        });
        
    } else {//不可用只能GG了
        NSLog(@"没有相机");
    }
}
#pragma mark - Album(相册流程与相机流程相同,相册是不存在硬件问题的,只要有权限就可以直接调用)
- (void)checkAlbumPermission {
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusNotDetermined) {
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (status == PHAuthorizationStatusAuthorized) {
                    [self selectAlbum];
                }
            });
        }];
    } else if (status == PHAuthorizationStatusDenied || status == PHAuthorizationStatusRestricted) {
        [self alertAlbum];
    } else {
        [self selectAlbum];
    }
}
- (void)selectAlbum {
    //判断相册是否可用
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        self.imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:self.imagePickerController animated:YES completion:^{
            
        }];
    }
}

- (void)alertAlbum {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"请在设置中打开相册" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:nil];
}
#pragma mark - 03.懒加载初始化弹框;
- (UIImagePickerController *)imagePickerController {
    if (_imagePickerController == nil) {
        _imagePickerController = [[UIImagePickerController alloc] init];
        _imagePickerController.modalPresentationStyle = UIModalPresentationFullScreen;
        _imagePickerController.delegate = self; //delegate遵循了两个代理
        _imagePickerController.allowsEditing = YES;
        _imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
    }
    return _imagePickerController;
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    NSMutableArray *arr = [NSMutableArray array];
    [arr addObject:image];
    NSString *uploadUrl = CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-tps-api",[ReAddressDynamic shared].baseUrl], FILE_UPLOAD);

    [HTTPManager postUploadFiles:uploadUrl file:arr fileName:@"file" withVC:self netName:@"文件上传" success:^(id response, NSString *msg) {
        
        if ([self.indexStr isEqualToString:@"1"]) {
            [self.sfzZButton sd_setBackgroundImageWithURL:response[@"data"] forState:(UIControlStateNormal)];
            self.fistImag = response[@"data"];
            [self OCRNetworking:response[@"data"]];
        }else{
            [self.sfzFButton sd_setBackgroundImageWithURL:response[@"data"] forState:(UIControlStateNormal)];
            self.twoImag = response[@"data"];
            [self OCRNetworking:response[@"data"]];
        }
        [self.imagePickerController dismissViewControllerAnimated:YES completion:^{
                    
                }];
        
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
}
- (void)OCRNetworking:(NSString *)string{
    NSDictionary *parmas = @{
        @"image": string,
        @"ocrType": @"ocrIdidentityCardFront",
        @"token":[UserDefaultUtil valueForKey:USER_TOKEN],
    };
    
    [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-tps-api",[ReAddressDynamic shared].baseUrl], NTOCC_OCRCARD) withParameter:parmas withVC:self netName:@"OCR识别" success:^(id response, NSString *msg) {
        
//        [XSInfoView showInfo:msg onView:self.view];
        //身份证
        if ([DCSpeedy isBlankString:response[@"name"]] == NO) {
//            _nameTF.text = response[@"name"];
            self.sfName = response[@"name"];
        }
        if ([DCSpeedy isBlankString:response[@"identity"]] == NO) {
//            _idCardTF.text = response[@"identity"];
            self.sfNumber = response[@"identity"];
        }
        
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
}

@end
